<!-- 活动信息收集 -->
<template>
  <div class="">
    <h5>活动信息收集</h5>
    <h6 class="linh-50 fw-6">当前活动：{{ title || activityInfo.title }}</h6>
    <div class="disFlxAC _mt-30 _mb-20">
      <span class="fw-6">报名基本信息：</span>
    </div>

    <div>
      <div v-if="fieldList.length" class="disFlx">
        <div class="fontTC" style="width: 11%">排序</div>
        <div class="fontTC" style="width: 23%">名称</div>
        <div class="fontTC" style="width: 23%">类型</div>
        <div class="fontTC" style="width: 23%">填写提示（选填）</div>
        <div class="fontTC" style="width: 10%">必填</div>
        <div class="fontTC" style="width: 10%">操作</div>
      </div>

      <Draggable v-model="fieldList" filter=".forbid" :animation="300" handle=".drag-icon" :move="onMove">
        <template v-for="(item, index) in fieldList">
          <div :class="index < 4 ? 'forbid' : ''" :key="index">
            <div>
              <div class="disFlx flexAStart _mt-10">
                <div class="fontTC" style="width: 11%">
                  <img
                    class="drag-icon"
                    src="@/assets/icons/drag.png"
                    alt=""
                    :style="{ opacity: index < 4 ? 0.5 : 1 }"
                  />
                </div>
                <div class="fontTC" style="width: 23%">
                  <a-input v-model="item.showName" style="width: 90%" :disabled="index < 4" />
                </div>
                <div class="fontTC" style="width: 23%">
                  <a-select
                    v-model="item.itemTypeId"
                    style="width: 90%"
                    :disabled="index < 4"
                    @change="val => handleChangeType(val, index)"
                  >
                    <a-select-option
                      v-for="option in typeList"
                      :value="option.id"
                      :key="option.id"
                      :disabled="option.enabled === 0"
                    >
                      {{ option.name }}
                    </a-select-option>
                  </a-select>
                  <div class="_mt-10 _ml-10" style="width: fit-content;">
                    <UploadFileMultiple
                      v-if="item.itemType === 'Attachment' && item.itemDefault"
                      :defaultFileList="item.itemDefault"
                      :maxNum="1"
                      @uploadSuccess="fileList => uploadFileMultipleSuccess(index, fileList)"
                    />
                  </div>
                </div>
                <div style="width: 23%">
                  <a-input v-model="item.value" style="width: 90%" :disabled="index < 4" />
                </div>

                <div class="fontTC" style="width: 10%">
                  <a-checkbox
                    v-model="item.isRequired"
                    :disabled="index < 2 || (index > 1 && index < 4 && !item.enabled)"
                  />
                </div>
                <div v-if="index >= 4" class="fontTC" style="width: 10%">
                  <a @click="handleDel(index)">删除</a>
                </div>
                <div v-if="index === 2 || index === 3" class="fontTC" style="width: 10%">
                  <a v-if="item.isShow" @click="handleShowOrHide(index)">点击隐藏</a>
                  <a v-else style="color: red" @click="handleShowOrHide(index)">已隐藏</a>
                </div>
              </div>
              <div
                v-if="
                  optionType.includes(item.itemType) &&
                    item.isInternalInterface !== 2 &&
                    item.customFormItemAnswerDtoList
                "
                class="disFlx"
                style="margin-left: 35%"
              >
                <span class="_mt-15 fw-6">选项内容：</span>
                <div class="_ml-10">
                  <div
                    class="disFlxAC _mt-10"
                    v-for="(option, subIndex) in item.customFormItemAnswerDtoList"
                    :key="subIndex"
                  >
                    <a-input class="width-30" v-model="option.words" placeholder="输入选项内容......" />
                    <a-icon
                      v-if="subIndex === 0"
                      type="plus-circle"
                      class="_ml-10 cup"
                      @click="handleAddOption(index)"
                    />
                    <a-icon v-else type="delete" class="_ml-10 cup" @click="handleDelOption(index, subIndex)" />
                  </div>
                </div>
              </div>
            </div>
            <div v-if="index === 3" class="disFlxAC _mt-30 _mb-20">
              <span class="fw-6">活动信息收集：</span>
              <a-button type="primary" @click="handleAddField">添加字段</a-button>
              <span class="_ml-20">
                拖动
                <img class="drag-icon" src="@/assets/icons/drag.png" alt="" />
                可调换字段顺序
              </span>
            </div>
          </div>
        </template>
      </Draggable>
    </div>

    <div class="fontTC _mt-30">
      <a-button size="large" type="primary" class="width-30" @click="handleSave">保存</a-button>
    </div>

    <SuccessModal
      ref="successModal"
      title="发布成功"
      desc="活动信息收集发布成功后，您可以选择返回列表，也可以选择继续配置活动其它相关信息！"
      :steps="['添加打印设备', '设置打印内容']"
      :close="closeSuccessModal"
      :confirm="confirmSuccessModal"
      confirmText="立即添加设备"
    />
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import SuccessModal from '@/components/SuccessModal/index.vue'
import UploadFileMultiple from '@/components/UploadFile/multiple.vue'
import { activityCustomFormItemTypeList } from '@/api/member/member'
import { FormById, AddOrUpdateForm, FormItemDeleteTip } from '@/api/activity/activity'
import { isObject } from 'lodash-es'
import { cancelActivityErr } from '@/utils/codes'
export default {
  components: {
    Draggable,
    SuccessModal,
    UploadFileMultiple
  },
  props: {
    activityInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      activityId: undefined,
      title: undefined,
      typeList: [],
      fieldList: [],
      optionType: ['Select', 'RadioGroup', 'CheckboxGroup']
    }
  },
  methods: {
    async getFormById() {
      let { data } = await FormById(this.activityId)
      let list = (data && data.formItemList) || []
      this.title = data.name
      this.fieldList = list.map(item => {
        if (item.itemType === 'Attachment' && item.itemDefault && item.itemDefault.length) {
          item.itemDefault = [JSON.parse(item.itemDefault[0])]
        }

        return {
          ...item,
          isRequired: item.isRequired === 1,
          customFormItemAnswerDtoList: item.customFormItemAnswerList || []
        }
      })
      this.fieldList.unshift(
        { showName: '姓名', itemTypeId: 1, value: '请输入姓名', isRequired: true },
        { showName: '手机号码', itemTypeId: 16, value: '请输入手机号码', isRequired: true },
        {
          showName: '单位名称',
          itemTypeId: 1,
          value: '请输入单位名称',
          isRequired: data.defaultFormItemDto.companyNameRequired === 1,
          isShow: data.defaultFormItemDto.companyNameShow === 1,
          enabled: data.defaultFormItemDto.companyNameShow === 1
        },
        {
          showName: '单位职务',
          itemTypeId: 1,
          value: '请输入单位职务',
          isRequired: data.defaultFormItemDto.companyPositionNameRequired === 1,
          isShow: data.defaultFormItemDto.companyPositionNameShow === 1,
          enabled: data.defaultFormItemDto.companyPositionNameShow === 1
        }
      )
    },
    async getCustomFormItemTypeList() {
      let res = await activityCustomFormItemTypeList()
      this.typeList = res.data || []
    },
    //添加常用字段
    handleAddDefaultField(item) {
      let index = this.fieldList.findIndex(f => f.showName === item.showName)
      if (index != -1) return this.$message.warning('请勿重复添加该字段')
      this.fieldList.push({ ...item, name: item.showName, sort: this.fieldList.length + 1 })
    },
    handleAddField() {
      this.fieldList.push({
        name: '',
        showName: '',
        itemTypeId: 1,
        itemType: 'Input',
        value: '',
        isRequired: false,
        sort: this.fieldList.length + 1
      })
    },
    async handleDel(index) {
      let item = this.fieldList[index]
      //没有id可以直接删除
      if (!item.id) {
        return this.fieldList.splice(index, 1)
      } else {
        let res = await FormItemDeleteTip({
          formItemId: item.id,
          activityId: this.activityId
        })

        if (res.code === cancelActivityErr) {
          this.$confirm({
            title: '字段删除提示',
            content: h => {
              return h(
                'div',
                JSON.parse(res.msg).map((item, index) => h('p', `${index + 1}：${item}`))
              )
            },
            okText: '依然删除',
            okType: 'danger',
            cancelText: '我再想想',
            onOk: () => {
              this.fieldList.splice(index, 1)
            }
          })
        } else {
          this.fieldList.splice(index, 1)
        }
      }
    },
    // 类型选择事件
    handleChangeType(val, index) {
      let field = this.fieldList[index]
      let item = this.typeList.find(f => f.id === val)

      if (this.optionType.includes(item.type)) {
        field.customFormItemAnswerDtoList = [
          {
            words: undefined
          }
        ]
      } else {
        field.customFormItemAnswerDtoList = []
      }
      field.itemType = item.type
      this.fieldList.splice(index, 1, field)

      if (field.itemType === 'Attachment') {
        this.$set(this.fieldList, index, { ...field, itemDefault: [], disabled: true })
      } else {
        this.$set(this.fieldList, index, { ...field, itemDefault: undefined, disabled: false })
      }
    },
    handleAddOption(index) {
      let field = this.fieldList[index]
      field.customFormItemAnswerDtoList.push({
        words: undefined
      })
      this.fieldList.splice(index, 1, field)
    },
    handleDelOption(index, subIndex) {
      let field = this.fieldList[index]
      field.customFormItemAnswerDtoList.splice(subIndex, 1)
      this.fieldList.splice(index, 1, field)
    },
    onMove(e) {
      if (e.relatedContext.index < 4) return false
      return true
    },
    //显示或隐藏
    handleShowOrHide(index) {
      let item = this.fieldList[index]
      item.isShow = !item.isShow
      item.enabled = item.isShow
      this.fieldList.splice(index, 1, item)
    },
    closeSuccessModal() {
      this.$refs.successModal.closeModal()
      this.$router.replace({
        path: '/activity/activityList'
      })
    },
    confirmSuccessModal() {
      this.$refs.successModal.closeModal()
      this.$emit('changeTitleKey', 'sign')
    },
    uploadFileMultipleSuccess(index, fileList) {
      this.$set(this.fieldList[index], 'itemDefault', fileList.length ? fileList : [])
    },
    //保存表单
    async handleSave() {
      if (this.fieldList.filter(f => !f.showName).length) return this.$message.error('请检查字段名称是否填写正确！')
      const attachments = this.fieldList.filter(item => item.itemType === 'Attachment')
      if (attachments.filter(item => !item.itemDefault || !item.itemDefault[0]).length) {
        return this.$message.error('必须上传附件才可以保存')
      }
      attachments.forEach(item => {
        if (isObject(item.itemDefault[0])) {
          item.itemDefault = [JSON.stringify(item.itemDefault[0])]
        }
      })

      let list = this.fieldList.slice(4)
      let companyName = this.fieldList[2]
      let companyPosition = this.fieldList[3]

      let { msg } = await AddOrUpdateForm({
        id: this.activityId,
        customFormItemList: list.map((item, index) => {
          return {
            ...item,
            isRequired: item.isRequired ? 1 : 0,
            name: item.showName,
            sort: index + 1
          }
        }),
        defaultFormItemDto: {
          companyNameRequired: companyName.isRequired ? 1 : 0,
          companyNameShow: companyName.isShow ? 1 : 0,
          companyPositionNameRequired: companyPosition.isRequired ? 1 : 0,
          companyPositionNameShow: companyPosition.isShow ? 1 : 0
        }
      })
      this.$refs.successModal.showModal()
      this.getFormById()
    }
  },
  activated() {
    let { activityId } = this.$route.query
    this.activityId = activityId
    this.getFormById()
    this.getCustomFormItemTypeList()
  },
  created() {},
  mounted() {}
}
</script>
<style scoped lang="less">
.field {
  .label {
    flex-shrink: 0;
  }
  .field-list {
    flex-wrap: wrap;
    .field-item {
      padding: 5px;
      border: 1px #eee solid;
      margin-right: 10px;
      margin-bottom: 10px;
      .icon {
        width: 20px;
        height: 20px;
      }
      .text {
        margin-left: 5px;
      }
    }
  }
}
</style>
